<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 订单以及售后中心
 * @author soubao 当燃
 *  @Date: 2016-12-20
 */
namespace app\api\controller;

use app\common\logic\CartLogic;
use app\common\model\OrderGoods;
use app\common\model\TeamFound;
use app\common\util\TpshopException;
use think\Db;
use think\Page;
use app\common\logic\OrderLogic;

class Order extends Base 
{
    /**
     * 退换货列表
     */
    public function return_goods_list()
    {
        //退换货商品信息
        $count = M('return_goods')->where("user_id", $this->user_id)->count();
        $pagesize = C('PAGESIZE');
        $page = new Page($count, $pagesize);
        $list = M('return_goods')->where("user_id", $this->user_id)->order("id desc")->limit("{$page->firstRow},{$page->listRows}")->select();
        $goods_id_arr = get_arr_column($list, 'goods_id');  //获取商品ID
        if (!empty($goods_id_arr)){
            $goodsList = M('goods')->where("goods_id", "in", implode(',', $goods_id_arr))->getField('goods_id,goods_name');
        }
        $state = C('REFUND_STATUS');
        $this->assign('goodsList', $goodsList);
        $this->assign('list', $list);
        $this->assign('state',$state);
        $this->assign('page', $page->show());// 赋值分页输出
        if (I('is_ajax')) {
            return $this->fetch('ajax_return_goods_list');
            exit;
        }
        return $this->fetch();
    }

    /**
     * 申请退货
     */
    public function return_goods()
    {
        $rec_id = I('rec_id',0);
        $order_id = I('order_id/d',0);
    	$goods_id = I('goods_id/d',0);
    	$spec_key = I('spec_key','');
    	
    	//判断是否重复提交申请售后
    	if($order_id && $goods_id){
    	    $return_goods = M('return_goods')
    	    ->where(['order_id'=>$order_id,'goods_id'=>$goods_id,'spec_key'=>$spec_key])
    	    ->where('status','in','0,1')->find();
    	    !empty($return_goods) && $this->ajaxReturn(['status'=>-1,'msg'=>'已经在申请退货中']);
    	}
    	
        $order_goods = M('order_goods')->where(array('rec_id'=>$rec_id))->find();
        $order = M('order')->where(array('order_id'=>$order_goods['order_id'],'user_id'=>$this->user_id))->find();
        if(!$order){
    	    $this->ajaxReturn(['status' => -1, 'msg' => "参数[$rec_id]无效", 'result' => '']);
    	}
        if(IS_POST){
            $model = new OrderLogic();
            $res = $model->addReturnGoods($rec_id,$order);  //申请售后
            $this->ajaxReturn($res);
        }
    
        $region_id[] = tpCache('shop_info.province');        
        $region_id[] = tpCache('shop_info.city');        
        $region_id[] = tpCache('shop_info.district');
        $region_id[] = 0;        
        $address_arr = M('region')->where("id in (".implode(',', $region_id).")")->getField('name',true);
        $return_address =implode($address_arr, '');
        $this->ajaxReturn(['status' => 1, 'msg' => "", 'result' => array(
                'goods_id'=>$order_goods['goods_id'],
                'goods_name'=>$order_goods['goods_name'],
                'goods_price' => $order_goods['goods_price'],
                'goods_num' => $order_goods['goods_num'],
                'spec_key' => $order_goods['spec_key'],
                'spec_key_name' => $order_goods['spec_key_name'],
                'order_id' => $order['order_id'],
                'order_sn' => $order['order_sn'],
                'store_name'=>tpCache('shop_info.store_name'),
                'store_address'=>$return_address.tpCache('shop_info.address'),
                'service_phone'=>tpCache('shop_info.phone')
            )]);
    }

    /**
     * 售后过期提示页面
     */
    public function return_error(){
        $phone = Db::name('config')->where(['name'=>'mobile'])->cache(true,TPSHOP_CACHE_TIME)->getField('value');
        $this->assign('phone', $phone);
        return $this->fetch();
    }


    /**
     * 取消详情
     * @return \think\mixed
     */
    public function cancel_order_info(){
        $order_id = I('order_id/d',0);
        $Order = new \app\common\model\Order();
        $order = $Order::get(['order_id'=>$order_id,'order_status'=>3,'pay_status'=>['gt',0]]);
        if(!$order){
            $this->error('非法操作！');
        }

        $this->assign('order',$order->toArray());
        return $this->fetch();
    }


    /**
     * 获取订单详情
     */
    public function order_detail()
    {
        if (!$this->user_id) {
            $this->ajaxReturn(['status'=>-1, 'msg'=>'还未登陆', 'result'=>'']);
        }
        
        $id = I('id/d');
        if ($id){
            $map['order_id'] = $id;
        } else {
            $map['order_sn'] = I('sn');//主订单号
        }
        $map['user_id'] = $this->user_id;

        $Order = new \app\common\model\Order();
        $orderObj = $Order->where($map)->find();
        if (!$orderObj) {
            $this->ajaxReturn(['status'=>-1,'msg'=>'订单不存在','result'=>'']);
        }
        //转为数字，并获取订单状态，订单状态显示按钮，订单商品
        if ($orderObj->prom_type == 6) {
            $orderTeamFound = $orderObj->teamFound;
            $order_info = $orderObj->append(['order_status_detail', 'order_button', 'order_goods'])->toArray();
            if ($orderTeamFound) {
                //团长的单
                $order_info['orderTeamFound'] = $orderTeamFound;//团长
            } else {
                //去找团长
                $TeamFound = new TeamFound();
                $teamFound = $TeamFound::get(['found_id' => $orderObj->teamFollow['found_id']]);
                $order_info['orderTeamFound'] = $teamFound;//团长
            }
        } else {
            $order_info = $orderObj->append(['order_status_detail', 'order_button', 'order_goods','virtual_order_button'])->toArray();
        }

        $invoice_no = M('DeliveryDoc')->where("order_id" , $order_info['order_id'])->getField('invoice_no',true);
        $order_info['invoice_no'] = implode(' , ', $invoice_no);
        // 获取 最新的 一次发货时间
        $order_info['shipping_time'] = M('DeliveryDoc')->where("order_id" , $order_info['order_id'])->order('id desc')->getField('create_time');        
        
        //虚拟订单兑换码
        if ($order_info['pay_status'] == 1 && $order_info['order_status'] != 3 && $order_info['prom_type'] == 5) {
            $vrorder = M('vr_order_code')->field('vr_state,vr_code,vr_indate,vr_usetime')->where(['order_id'=>$id])->select();
        }
        $order_info['vrorder'] = $vrorder ?: [];
            
        //订单收货地址
        $order_info['total_address'] = getTotalAddress($order_info['province'], $order_info['city'], $order_info['district'], $order_info['twon'], $order_info['address']);

        //返回商品规格组合id(item_id)
        foreach ($order_info['order_goods'] as &$v){
            if($v['spec_key']){
                $item_id = M("SpecGoodsPrice")->where(['key' => $v['spec_key'],'goods_id'=>$v['goods_id']])->getField('item_id');
            }
            $v['item_id'] = empty($item_id) ? 0 : $item_id;
            $rgId = Db::name('ReturnGoods')->where(['rec_id'=>$v['rec_id']] )->getField('id');
            $v['exchange_integral'] = Db::name('goods')->where(['goods_id'=>$v['goods_id']] )->getField('exchange_integral');
            $v['return_id'] = 0;
            $rgId && $v['return_id'] =$rgId;   //退款详情ID
        }
        $this->ajaxReturn(['status'=>1,'msg'=>'获取成功','result'=>$order_info]);
    }
    
    /**
     * 删除订单
     */
    public function del_order()
    {
        $order_id = I('post.order_id', 0);
        $order = new  \app\common\logic\Order();
        try{
            $order->setOrderById($order_id);
            $order->setUserId($this->user_id);
            $order->userDelOrder();
            $this->ajaxReturn(['status' => 1, 'msg' => '删除成功']);
        }catch (TpshopException $t){
            $error = $t->getErrorArr();
            $this->ajaxReturn($error);
        }
    }
    
    /**
     *  退货详情
     */
    public function return_goods_info()
    {
        $id = I('id/d', 0);
        $return_goods = M('return_goods')->where("id = $id")->find();
        $return_goods['seller_delivery'] = unserialize($return_goods['seller_delivery']);  //订单的物流信息，服务类型为换货会显示
        $return_goods['imgs'] = $return_goods['imgs'] ? explode(',', $return_goods['imgs']) : [];
        $goods = M('goods')->field('goods_id,goods_name,shop_price')->where("goods_id", $return_goods['goods_id'])->find();
        $state = C('REFUND_STATUS');
        $return_type = C('RETURN_TYPE');

        //若是json请求
        if (I('is_json')) {
            $return_goods['status_name'] = $state[$return_goods['status']];
            $this->ajaxReturn(['status' => 1, 'msg' => '获取成功',
                'result' => [
                    'return_goods' => $return_goods,
                    'goods' => $goods
                ]
            ]);
        }
        
        $this->assign('state',$state);
        $this->assign('return_type',$return_type);
        $this->assign('goods', $goods);
        $this->assign('return_goods', $return_goods);
        return $this->fetch();
    }

    /**
     * 修改退货状态，发货
     */
    public function checkReturnInfo()
    {
        $data = [];
        $data['id'] = I('id');
        $data['express_time'] = I('express_time');
        $data['delivery'] = [];
        $data['delivery']['express_name'] = serialize($data['express_name']);
        $data['delivery']['express_fee'] = serialize($data['express_fee']);
        $data['delivery']['express_sn'] = serialize($data['express_sn']);
        $data['status'] = 2;
        $res = M('return_goods')->where(['id'=>$data['id'],'user_id'=>$this->user_id])->save($data);
        if($res !== false){
            $this->ajaxReturn(['status'=>1,'msg'=>'发货提交成功','url'=>U('Mobile/Order/return_goods_info',['id'=>$data['id']])]);
        }else{
            $this->ajaxReturn(['status'=>-1,'msg'=>'提交失败','url'=>'']);
        }
    }

    /**
     * 取消售后服务
     * @author lxl
     * @time 2017-4-19
     */
    public function return_goods_cancel()
    {
        $id = I('id',0);
        if(empty($id))$this->ajaxReturn(['status'=>-1,'msg'=>'参数错误']);
        $return_goods = M('return_goods')->where(array('id'=>$id,'user_id'=>$this->user_id))->find();
        if(empty($return_goods)) $this->ajaxReturn(['status'=>-1,'msg'=>'参数错误']);
        $res= M('return_goods')->where(array('id'=>$id))->save(array('status'=>-2,'canceltime'=>time()));
        if ($res !== false){
            $this->ajaxReturn(['status'=>1,'msg'=>'取消成功']);
        }else{
            $this->ajaxReturn(['status'=>-1,'msg'=>'取消失败']);
        }
    }
    
    /**
     * 申请退货状态
     */
    public function return_goods_status()
    {
        $rec_id = I('rec_id','');
        $return_goods = M('return_goods')
            ->where(['rec_id'=>$rec_id])
            ->find();
        $return_id = $return_goods ? $return_goods['id'] : 0; //0代表未退换货
        $this->ajaxReturn(['status'=>1, 'msg'=>'获取成功',  'result' => $return_id]);
    }

    
    /**
     * 换货商品确认收货
     * @author lxl
     * @time  17-4-25
     * */
    public function receiveConfirm()
    {
        $is_json = I('is_json', 0);
        $return_id=I('return_id/d');
        $return_info=M('return_goods')->field('order_id,order_sn,goods_id,spec_key')->where('id',$return_id)->find(); //查找退换货商品信息
        $update = M('return_goods')->where('id',$return_id)->save(['status'=>3]);  //要更新状态为已完成
        if($update) {
            M('order_goods')->where(array(
                'order_id' => $return_info['order_id'],
                'goods_id' => $return_info['goods_id'],
                'spec_key' => $return_info['spec_key']))->save(['is_send' => 2]);  //订单商品改为已换货
            if ($is_json) {
                $this->ajaxReturn(['status' => 1, 'msg' => '操作成功']);
            }
            $this->success("操作成功", U("order/return_goods_info", array('id' => $return_id)));
        }
        
        if ($is_json) {
            $this->ajaxReturn(['status' => -1, 'msg' => '操作失败']);
        }
        $this->error("操作失败");
    }
    
    //订单支付后取消订单
    public function refund_order()
    {
        $order_id   = input('post.order_id', 0);
        $user_note  = input('post.user_note');
        $consignee  = input('post.consignee');
        $mobile     = input('post.mobile');

        $logic = new \app\common\logic\OrderLogic;
        $return = $logic->recordRefundOrder($this->user_id, $order_id, $user_note, $consignee, $mobile);

        $this->ajaxReturn($return);
    }
    
    /**
     * 上传退换货图片，兼容小程序
     */
    public function upload_return_goods_img()
    {
        $logic = new \app\common\logic\OrderLogic;
        $return = $logic->uploadReturnGoodsImg();
        $this->ajaxReturn($return);
    }

    //拼团订单列表
    public function team_list(){
        $type = input('type');
        $p = input('p', 1);
        $Order = new \app\common\model\Order();
        $order_where = ['prom_type' => 6, 'user_id' => $this->user_id, 'deleted' => 0,'pay_code'=>['<>','cod']];//拼团基础查询
        $listRows = 10;
        switch (strval($type)) {
            case 'WAITPAY':
                //待支付订单
                $order_where['pay_status'] = 0;
                $order_where['order_status'] = 0;
                break;
            case 'WAITTEAM':
                //待成团订单
                $found_order_id = Db::name('team_found')->where(['user_id'=>$this->user_id,'status'=>1])->limit($listRows)->order('found_id desc')->getField('order_id',true);//团长待成团
                $follow_order_id = Db::name('team_follow')->where(['follow_user_id'=>$this->user_id,'status'=>1])->limit($listRows)->order('follow_id desc')->getField('order_id',true);//团员待成团
                $team_order_id = array_merge($found_order_id,$follow_order_id);
                if (count($team_order_id) > 0) {
                    $order_where['order_id'] = ['in', $team_order_id];
                }else{
                    $order_where['order_id'] = 0;
                }
                break;
            case 'WAITSEND':
                //待发货
                $order_where['pay_status'] = 1;
                $order_where['shipping_status'] = ['<>',1];
                $order_where['order_status'] = ['elt',1];
                $found_order_id = Db::name('team_found')->where(['user_id'=>$this->user_id,'status'=>2])->limit($listRows)->order('found_id desc')->getField('order_id',true);
                $follow_order_id = Db::name('team_follow')->where(['follow_user_id'=>$this->user_id,'status'=>2])->limit($listRows)->order('follow_id desc')->getField('order_id',true);
                $team_order_id = array_merge($found_order_id,$follow_order_id);
                if (count($team_order_id) > 0) {
                    $order_where['order_id'] = ['in', $team_order_id];
                }else{
                    $order_where['order_id'] = 0;
                }
                break;
            case 'WAITRECEIVE':
                //待收货
                $order_where['shipping_status'] = 1;
                $order_where['order_status'] = 1;
                break;
            case 'WAITCCOMMENT':
                //已完成
                $order_where['order_status'] = 2;
                break;
        }
        $order_list = $Order->with('orderGoods')->where($order_where)->page($p, 10)->order('order_id desc')->select();
        if($order_list){
            $order_list = collection($order_list)->append(['order_status_detail','order_goods','order_button'])->toArray();
        }
        $this->ajaxReturn(['status'=>1,'msg'=>'获取成功','result'=>$order_list]);
    }

    /**
     * 再来一单
     */
    public function oneMore()
    {
        $order_id = input('order_id');
        $order_goods_list = OrderGoods::all(['order_id' => $order_id]);
        if (empty($order_goods_list)) {
            $this->ajaxReturn(['status' => 0, 'msg' => '订单商品不存在']);
        }
        $cartLogic = new CartLogic();
        $cartLogic->setUserId($this->user_id);
        $error_list = [];
        $order_goods_list_count = count($order_goods_list);
        $url = '';
        foreach ($order_goods_list as $order_goods) {
            $cartLogic->setGoodsModel($order_goods['goods_id']);
            $cartLogic->setSpecGoodsPriceByKey($order_goods['spec_key']);
            $cartLogic->setGoodsBuyNum(1);
            try {
                $cartLogic->addGoodsToCart();
            } catch (TpshopException $t) {
                $error = $t->getErrorArr();
                $error_list[] = $order_goods['goods_name'] . $order_goods['spec_key_name'] . $error['msg'];
                $url = $error['result']['url'] ? $error['result']['url'] : '';
            }
        }
        if ($order_goods_list_count != count($error_list)) {
            $this->ajaxReturn(['status' => 1, 'msg' => '加入购物车成功', 'result' => ['error_list' => $error_list, 'url' => $url]]);
        } else {
            $this->ajaxReturn(['status' => 0, 'msg' => '加入购物车失败', 'result' => ['error_list' => $error_list, 'url' => $url]]);
        }
    }
}